<template>
  <el-drawer
      :title="`${form.sendUserId_dictText || ''}发起的派单`"
      v-model="visible"
      size="60%"
      direction="rtl"
      :with-header="true"
  >
    <div style="padding: 10px">
      <el-card class="box-shadow">
        <el-descriptions title="" direction="vertical">
          <el-descriptions-item label="提交时间">{{ formatDate(form.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="发起人">{{ form.sendUserId_dictText }}</el-descriptions-item>
          <el-descriptions-item label="发起人部门">{{ form.sendDeptId_dictText }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 查看模式 -->
      <div v-if="!isEdit">
        <el-card class="box-shadow">
          <el-descriptions class="margin-top" title="派单" :column="3" direction="vertical">
            <el-descriptions-item label="工单类型" span="3">{{ form.type }}</el-descriptions-item>
            <el-descriptions-item label="明细" span="3">
              <el-card class="box-shadow">
                <template #header>
                  <div class="clearfix">
                    <span>明细数据</span>
                    <span style="float: right; padding: 3px 0">工单总分值：{{ score }}</span>
                  </div>
                </template>
                <el-table :data="detailsList" style="width: 100%">
                  <el-table-column prop="name" label="内容" min-width="25%"/>
                  <el-table-column prop="columnDesc" label="描述" min-width="30%"/>
                  <el-table-column prop="scope" label="对应分值" min-width="10%">
                    <template #default="scope">
                      {{ scope.row.score + '分' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="demandNum" label="数量" min-width="15%">
                    <template #default="scope">
                      <el-input-number
                          :min="0"
                          v-model="scope.row.demandNum"
                          placeholder="请输入数量"
                          disabled
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                      prop="finishNum"
                      label="实际完成数量"
                      min-width="15%"
                      v-if="finishState.includes(form.state)"
                  >
                    <template #default="scope">
                      <el-input-number
                          :min="0"
                          v-model="scope.row.finishNum"
                          placeholder="请输入数量"
                          disabled
                      />
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-descriptions-item>

            <el-descriptions-item label="产品名称">{{ form.productName }}</el-descriptions-item>
            <el-descriptions-item label="产品编码">{{ form.productCode }}</el-descriptions-item>
            <el-descriptions-item label="优先级">
              <dict-tag :type="DICT_TYPE.BUSINESS_PRIORITY" :value="form.priority||''"/>
            </el-descriptions-item>
            <el-descriptions-item label="派单要求处理时间">{{ form.sendEndDatetime }}</el-descriptions-item>
            <el-descriptions-item label="需求图片">
              <image-preview :src="form.demandImg" multiple/>
            </el-descriptions-item>
            <el-descriptions-item label="需求附件">
              <upload-file
                  v-model="form.demandFile"
                  :disabled="true"
                  :isShowTip="false"
              />
            </el-descriptions-item>
            <el-descriptions-item label="需求描述">
              <div v-html="form.demandDesc"></div>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card class="box-shadow">
          <el-descriptions class="margin-top" title="接单情况" :column="2" direction="vertical">
            <el-divider/>
            <el-descriptions-item label="接单人">{{ form.takeUserId_dictText }}</el-descriptions-item>
            <el-descriptions-item label="接单时间">{{ formatDate(form.takeDatetime) }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card class="box-shadow">
          <el-descriptions class="margin-top" title="处理情况" :column="2" direction="vertical">
            <el-divider/>
            <el-descriptions-item label="完成日期">{{ formatDate(form.finishDatetime) }}</el-descriptions-item>
            <el-descriptions-item label="完成结果">{{ form.finishResult }}</el-descriptions-item>
            <el-descriptions-item label="交付路径">{{ form.finishPath }}</el-descriptions-item>
            <el-descriptions-item label="完成图片">
              <image-preview :src="form.finishImg" multiple/>
            </el-descriptions-item>
            <el-descriptions-item label="处理附件">
              <upload-file
                  v-model="form.finishImg"
                  :disabled="true"
                  :isShowTip="false"
              />
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>

      <!-- 编辑模式 -->
      <div v-else>
        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
        >
          <el-card class="box-shadow">
            <template #header>
              <div class="clearfix">
                <span>派单</span>
              </div>
            </template>

            <el-form-item label="工单类型" prop="type">
              <el-radio-group
                  v-model="form.type"
                  @change="handleTypeChange"
              >
                <el-radio-button
                    v-for="item in typeList"
                    :key="item.type"
                    :label="item.type"
                >
                  {{ item.type }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-card class="box-shadow">
              <template #header>
                <div class="clearfix">
                  <span>明细数据</span>
                  <span style="float: right; padding: 3px 0">工单总分值：{{ score }}</span>
                </div>
              </template>
              <el-table :data="detailsList" style="width: 100%">
                <el-table-column prop="name" label="内容" min-width="25%"/>
                <el-table-column prop="columnDesc" label="描述" min-width="30%"/>
                <el-table-column prop="scope" label="对应分值" min-width="10%">
                  <template #default="scope">
                    {{ scope.row.score + '分' }}
                  </template>
                </el-table-column>
                <el-table-column prop="demandNum" label="需求数量" min-width="15%">
                  <template #default="scope">
                    <el-input-number
                        :min="0"
                        v-model="scope.row.demandNum"
                        placeholder="请输入数量"
                        :disabled="finishState.includes(form.state)"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                    prop="finishNum"
                    label="实际完成数量"
                    min-width="15%"
                    v-if="finishState.includes(form.state)"
                >
                  <template #default="scope">
                    <el-input-number
                        :min="0"
                        v-model="scope.row.finishNum"
                        placeholder="请输入数量"
                        :controls="false"
                        :step="1"
                        @change="handleNumChange($event, scope.$index)"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-card>

            <el-divider/>

            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="form.productName" placeholder="请输入产品名称"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产品编码" prop="productCode">
                  <el-input v-model="form.productCode" placeholder="请输入产品编码"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item label="优先级" prop="priority">

                  <el-radio-group v-model="form.priority">
                    <el-radio
                        v-for="dict in getDictOptions(DICT_TYPE.BUSINESS_PRIORITY)"
                        :key="dict.value"
                        :label="dict.label"
                    >
                      {{ dict.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="派单人员" prop="sendUserId">
                  <cascader-user
                      v-model="form.sendUserId"
                      disabled
                      placeholder="请输入派单人员"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="派单部门" prop="sendDeptId">
                  <cascader-dept
                      v-model="form.sendDeptId"
                      placeholder="请输入派单部门"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="需求描述" prop="demandDesc">
              <editor v-model="form.demandDesc" placeholder="请输入内容" :height="300"/>
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="需求图片" prop="demandImg">
                  <upload-imgs v-model="form.demandImg"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="需求附件" prop="demandFile">
                  <upload-file v-model="form.demandFile" placeholder="请输入需求附件"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="预计完成时间" prop="sendEndDatetime">
                  <el-date-picker
                      v-model="form.sendEndDatetime"
                      type="datetime"
                      value-format="x"
                      placeholder="选择发起预计处理完成时间"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 接单情况 -->
          <el-card class="box-shadow">
            <template #header>
              <div class="clearfix">
                <span>接单情况</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="接单人" prop="takeUserId">
                  <cascader-user
                      v-model="form.takeUserId"
                      placeholder="请输入接单人员"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="接单时间" prop="takeDatetime">
                  <el-date-picker
                      v-model="form.takeDatetime"
                      type="datetime"
                      value-format="x"
                      placeholder="选择发起预计处理完成时间"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="预计完成时间" prop="takeEndDatetime">
                  <el-date-picker
                      clearable
                      v-model="form.takeEndDatetime"
                      type="datetime"
                      value-format="x"
                      placeholder="请选择预计处理完成时间"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 处理情况 -->
          <el-card class="box-shadow">
            <template #header>
              <div class="clearfix">
                <span>处理情况</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="完成时间" prop="finishDatetime">
                  <el-date-picker
                      clearable
                      v-model="form.finishDatetime"
                      type="datetime"
                      value-format="x"
                      placeholder="请选择完成时间"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="完成结果" prop="finishResult">
                  <el-input
                      type="textarea"
                      v-model="form.finishResult"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                  <el-form-item label="交付路径" prop="finishPath">
                      <el-input
                              type="textarea"
                              v-model="form.finishPath"
                              style="width: 100%"
                      />
                  </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="完成图片" prop="finishImg">
                  <upload-imgs v-model="form.finishImg"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="完成文件" prop="finishFile">
                  <upload-file v-model="form.finishFile"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 审核情况 -->
          <el-card class="box-shadow">
            <template #header>
              <div class="clearfix">
                <span>审核情况</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="审核时间" prop="auditDatetime">
                  <el-date-picker
                      clearable
                      v-model="form.auditDatetime"
                      type="datetime"
                      value-format="x"
                      placeholder="请选择审核时间"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="审核结果" prop="auditResult">
                  <el-radio-group v-model="form.auditResult" size="small" disabled>
                    <el-radio label="agree" border>同意</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                    label="审核备注"
                    :prop="form.auditResult !== 'reject' ? '' : 'auditRemark'"
                >
                  <el-input type="textarea" v-model="form.auditRemark"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>

          <!-- 工单状态 -->
          <el-card class="box-shadow">
            <template #header>
              <div class="clearfix">
                <span>工单状态</span>
              </div>
            </template>
            <el-form-item label="" prop="state">
              <el-radio-group v-model="form.state">
                <el-radio
                    v-for="dict in getDictOptions(DICT_TYPE.BUSINESS_FLOW_STATUS)"
                    :key="dict.value"
                    :label="dict.value"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-card>
        </el-form>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="drawer-footer">
      <el-button
          type="primary"
          v-show="isEdit"
          @click="submitForm"
      >保存
      </el-button>
      <el-button v-show="isEdit" @click="isEdit = !isEdit">取 消</el-button>
      <el-button
          type="primary"
          v-show="!isEdit"
          @click="handleEdit"
      >编辑
      </el-button>
    </div>
  </el-drawer>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from 'vue';
import {VisualOrderApi} from "@/api/business/design/visual";
import {FormInfoApi} from "@/api/business/general/form";
import {DICT_TYPE, getDictOptions} from "@/utils/dict";
import {formatDate} from "@/utils/formatTime";
import {useUserStore} from "@/store/modules/user";
import {hasPermission} from "@/directives/permission/hasPermi";

const userStore = useUserStore()
const message = useMessage() // 消息弹窗
// 初始化响应式状态
const visible = ref(false);
const isEdit = ref(false);
const rootId = ref();
const formRef = ref(); // 表单引用
const form = ref({
  createTime: '',
  sendUserId_dictText: '',
  sendDeptId_dictText: '',
  type: '',
  productCode: '',
  productName: '',
  priority: '',
  sendEndDatetime: '',
  demandImg: '',
  demandFile: '',
  demandDesc: '',
  takeUserId: '',
  takeUserId_dictText: '',
  takeDatetime: '',
  takeEndDatetime: '',
  finishDatetime: '',
  finishResult: '',
  finishImg: '',
  finishFile: '',
    finishPath:'',
  auditDatetime: '',
  auditResult: 'agree',
  auditRemark: '',
  state: '',
  details: '[]' // 初始化为空JSON字符串
});
const typeList = ref({});
const detailsList = ref([]);
const finishState = ref(['audit', 'finish']);

// 表单验证规则
const rules = reactive({
  sendUserId: [
    {required: true, message: '请选择派单人员', trigger: 'blur'}
  ],
  state: [
    {required: true, message: '请选择工单状态', trigger: 'blur'}
  ]
});


const score = computed(() => {
  let total = 0;
  if (finishState.value.includes(form.value.state)) {
    detailsList.value.forEach(item => {
      const itemScore = Number(item.score) || 0;
      const itemFinishNum = Number(item.finishNum) || 0;
      // 分步计算并修正每一步的精度
      total += Math.round(itemScore * itemFinishNum * 100) / 100;
    });
  } else {
    detailsList.value.forEach(item => {
      const itemScore = Number(item.score) || 0;
      const itemDemandNum = Number(item.demandNum) || 0;
      // 分步计算并修正每一步的精度
      total += Math.round(itemScore * itemDemandNum * 100) / 100;
    });
  }
  // 对最终结果再做一次精度修正，确保只保留两位小数
  return Math.round(total * 100) / 100;
});

const showVisible = (type, row) => {
  visible.value = true;
  isEdit.value = false;
  form.value = row

  // 转换时间字段：将字符串格式的日期转换为时间戳（毫秒）
  // 解决编辑时日期变成 1970-01-01 的问题
  const timeFields = ['sendEndDatetime', 'takeEndDatetime', 'deliveryDatetime', 'takeDatetime', 'finishDatetime', 'auditDatetime'];
  timeFields.forEach(field => {
    if (form.value[field]) {
      // 如果是字符串格式的日期，转换为时间戳
      if (typeof form.value[field] === 'string') {
        const timestamp = new Date(form.value[field]).getTime();
        // 只有当转换结果是有效数字时才赋值，否则清空
        form.value[field] = !isNaN(timestamp) ? timestamp : undefined;
      }
    }
  });

  // 初始化预计完成时间
  if (!form.value.takeEndDatetime) {
    form.value.takeEndDatetime = form.value.sendEndDatetime || '';
  }

  // 解析明细数据（JSON字符串转数组）
  detailsList.value = form.value.details ? JSON.parse(form.value.details) : [];
  // 获取工单类型列表
  getTypeFormInfo();
  // 处理编辑模式
  if (type === 'edit') {
    isEdit.value = true;
  }
  // 获取可视化部门ID
  // getVisualDeptId();
};
//
// // 获取可视化部门ID（对应原getVisualDeptId）
// const getVisualDeptId = async () => {
//   try {
//     const res = await getConfigKey('workOrder.visual.deptId');
//     rootId.value = res.msg;
//   } catch (error) {
//     console.error('获取可视化部门ID失败：', error);
//     ElMessage.error('获取部门配置失败');
//   }
// };

// 提交表单（对应原submitForm）
const submitForm = async () => {
      // 表单验证
      await formRef.value.validate();

      // 处理明细数据（数组转JSON字符串）
      form.value.details = JSON.stringify(detailsList.value);
      // 处理需求图片（数组转字符串）
      if (Array.isArray(form.value.demandImg)) {
        form.value.demandImg = form.value.demandImg.join(',')
      }
      // 处理需求附件（数组转字符串）
      if (Array.isArray(form.value.demandFile)) {
        form.value.demandFile = form.value.demandFile.join(',')
      }

      if (Array.isArray(form.value.finishImg)) {
        form.value.finishImg = form.value.finishImg.join(',')
      }
      // 处理需求附件（数组转字符串）
      if (Array.isArray(form.value.finishFile)) {
        form.value.finishFile = form.value.finishFile.join(',')
      }

      // 赋值总分值
      form.value.score = score.value;
      // 调用更新接口
      await VisualOrderApi.updateVisualOrder(form.value);
      visible.value = false;
      emit('success');

    }
;

// 获取工单类型列表（对应原getTypeFormInfo）
const getTypeFormInfo = async () => {
  try {
    const res = await FormInfoApi.getFormInfoPage({module: 'visual'});
    typeList.value = res.list
  } catch (error) {

  }
};

// 工单类型变更（对应原handleTypeChange）
const handleTypeChange = (val) => {
  FormInfoApi.getFormDetailsListByType(val).then(res => {
    detailsList.value = res.map(item => ({
      name: item.name,
      columnDesc: item.columnDesc,
      score: item.score,
      demandNum: 0
    }))
  })
}

// 编辑权限校验（对应原handleEdit）
const handleEdit = () => {
  if (userStore.user.id == form.value.sendUserId || hasPermission(['design:visual-order:admin'])) {
    isEdit.value = true;
  } else {
    message.error('您没有权限进行此操作');
  }
};

// 完成数量变更（对应原handleNumChange）

const handleNumChange = (value, index) => {
  // 确保 value 是数字且不小于 0
  if (value === null || isNaN(value)) {
    value = 0;
  }
  detailsList.value[index].demandNum = Math.floor(value).toFixed(2);
}

onMounted(async () => {
});

// 定义组件事件（向父组件传值）
const emit = defineEmits(['success']);

// 暴露组件方法（供父组件调用）
defineExpose({showVisible});
</script>

<style scoped>
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  padding: 16px;
  gap: 8px;
  border-top: 1px solid #eee;
}

.box-shadow {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  margin-bottom: 16px;
}

.margin-top {
  margin-top: 16px;
}
</style>
